package org.batatasframework.values;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Date;
import java.util.List;

import org.batatasframework.util.BytesUtils;

/**
 * 存储的是byte数组，需要把byte数组与各类型进行转换
 * 
 * 主要针对公共字段的数据存储值
 * @author jackson
 *
 */
public class BytesValueGetter implements ValueGetter{
	
	public static ValueGetter valueOf(byte[] sourceValue){
		if(null == sourceValue) return NullValueGetter.nullValue();
		return new BytesValueGetter(sourceValue);
	}
	
	/** 需要被转成各类值的字符串 */
	protected final byte[] sourceValue;
	
	protected BytesValueGetter(){
		this.sourceValue = null;
	}
	
	protected BytesValueGetter(byte[] sourceValue){
		this.sourceValue = sourceValue;
	}
	
	@Override
	public boolean is(Object target) {
		return target.equals(sourceValue);
	}

	@Override
	public String getString() {
		return new String(sourceValue);
	}

	@Override
	public Integer getInteger() {
		return BytesUtils.toInt(sourceValue);
	}

	@Override
	public Long getLong() {
		return BytesUtils.toLong(sourceValue);
	}

	@Override
	public Boolean getBoolean() {
		if(null != sourceValue && sourceValue.length > 0) 
			return sourceValue[0] == 1;
		return null;
	}

	@Override
	public Double getDouble() {
		return BytesUtils.toDouble(sourceValue);
	}

	@Override
	public <T> T getObject(Class<T> clazz) {
		try {
			ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(sourceValue));
			return clazz.cast(oin.readObject());
		} catch (Exception e) {
			// nothing to do
		}
		return null;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> List<T> asList() {
		return getObject(List.class);
	}
	
	@Override
	public Class<?> getClassType() {
		return getObject(Class.class);
	}

	@Override
	public Date getDate(Object arg) {
		return getObject(Date.class);
	}

	@Override
	public <E extends Enum<E>> E toEnum(Class<E> clazz) {
		return getObject(clazz);
	}
	
}
